package com.shop.service.impl.security;

import com.shop.entity.Manager;
import com.shop.entity.security.AccountUser;
import com.shop.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userDetailService")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    ManagerService managerService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Manager manager = managerService.getUsername(username);

        if (manager == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        return new AccountUser(manager.getId(),  manager.getUsername(), manager.getPassword(),  getUserAuthority(manager.getId()));
    }

    public List<GrantedAuthority> getUserAuthority(Integer id) {
        String authority = managerService.getUserAuthorityInfo(id);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
